<?php

/**
 * 文章管理操作类
 * @author 祝文博<kevinroot@163.com>
 * @create 2013-05-08 20:37:32
 */
class Business_Article
{

    protected $_articleTableInfo;

    protected $_table;

    protected static $_instance;

    public static function getInstance()
    {
        if (empty(self::$_instance)) {
            self::$_instance = new Business_Article();
        }
        return self::$_instance;
    }

    public function __construct()
    {
        $this->_articleTableInfo = Zend_Registry::get('database')->article;
        $this->_table = Zend_Registry::get('database')->article->tablename;
    }

    /**
     * 根据类型获取文章的数量
     * 
     * @param int $type
     *            类型
     *            0时获得所有类型记录条数
     */
    public function getArticleAmount($type, $author = null, $date = null, $tag = null)
    {
        $select = Utility_Db::getInstance()->conn()->select();
        $select->from($this->_table);
        if (! empty($type)) {
            $typeMap = Zend_Registry::get('config')->menu;
            if ($type == $typeMap->mix) {
                if (null != $author) {
                    $select->where($this->_articleTableInfo->author . '=?', $author);
                }
                if (null != $date) {
                    $select->where($this->_articleTableInfo->ctime . ' like ?', $date . '%');
                }
                if (null != $tag) {
                    $select->where($this->_articleTableInfo->keywords . ' like ?', '%' . $tag . '%');
                }
            } else {
                $select->where($this->_articleTableInfo->type . '=?', $type);
            }
        }
        $list = $select->query()->fetchAll();
        return count($list);
    }

    /**
     * 根据类型获取文章
     * 
     * @param int $type
     *            类型
     * @param int $page
     *            页码
     * @param int $rowCount
     *            每页有多少文章
     */
    public function getArticleList($type, $page = null, $rowCount = null, 
        $orderby = null, $author = null, $date = null, $tag = null)
    {
        $cond = array(
            $this->_articleTableInfo->id,
            $this->_articleTableInfo->ctime,
            $this->_articleTableInfo->mtime,
            $this->_articleTableInfo->title,
            $this->_articleTableInfo->description,
            $this->_articleTableInfo->keywords,
            $this->_articleTableInfo->coverimage,
            $this->_articleTableInfo->type,
            $this->_articleTableInfo->author,
            $this->_articleTableInfo->url
        );
        $select = Utility_Db::getInstance()->conn()->select();
        $select->from($this->_table, $cond);
        if (! empty($type)) {
            $typeMap = Zend_Registry::get('config')->menu;
            if ($type == $typeMap->mix) {
                if (null != $author) {
                    $select->where($this->_articleTableInfo->author . '=?', $author);
                }
                if (null != $date) {
                    $select->where($this->_articleTableInfo->ctime . ' like ?', $date . '%');
                }
                if (null != $tag) {
                    $select->where($this->_articleTableInfo->keywords . ' like ?', '%' . $tag . '%');
                }
            } else {
                $select->where($this->_articleTableInfo->type . '=?', $type);
            }
        }
        $list = $select->limitPage($page, $rowCount)
            ->order($orderby . " DESC")
            ->query()
            ->fetchAll();
        return $list;
    }

    /**
     * 获取文章的详细内容
     * 
     * @param int $id            
     */
    public function getArticleDetails($id)
    {
        $articleDetail = Utility_Db::getInstance()->conn()
            ->select()
            ->from($this->_table)
            ->where($this->_articleTableInfo->id . '=?', $id)
            ->query()
            ->fetch();
        return $articleDetail;
    }
    
    // 以下是祝文博写的
    /**
     * 保存文章
     * 
     * @param Array $data            
     * @return boolean
     */
    public function save($data)
    {
        if (empty($data[$this->_articleTableInfo->id])) {
            unset($data[$this->_articleTableInfo->id]);
        }
        
        $data[$this->_articleTableInfo->ctime] = date("Y-m-d H:i:s");
        $data[$this->_articleTableInfo->mtime] = date("Y-m-d H:i:s");
        
        $db = Utility_Db::getInstance()->conn();
        try {
            $insRowNum = $db->insert($this->_table, $data);
            if ($insRowNum) {
                $articleid = $db->lastInsertId();
                $tags = explode(',', $data[$this->_articleTableInfo->keywords]);
                $rtn = $this->setTags($articleid, $tags);
            } else {
                $rtn = array(
                    'errorcode' => - 1,
                    'errormsg' => 'failed'
                );
            }
        } catch (Zend_Db_Exception $exp) {
            if ($exp->getCode() == 1062) {
                $articleid = $data[$this->_articleTableInfo->id];
                $where = array(
                    $this->_articleTableInfo->id . ' = ?' => $articleid
                );
                unset($data[$this->_articleTableInfo->id]);
                unset($data[$this->_articleTableInfo->ctime]);
                $affectRows = $db->update($this->_table, $data, $where);
                if ($affectRows) {
                    $tmpNewTags = explode(',', $data[$this->_articleTableInfo->keywords]);
                    $newTags = array();
                    foreach ($tmpNewTags as $newTag) {
                        $newTags[] = urlencode($newTag);
                    }
                    $oldTags = Business_Tags::getInstance()->getTagsInUrlencode($articleid);
                    $noChangedTags = array_intersect($newTags, $oldTags);
                    
                    $addTags = array_diff($newTags, $noChangedTags);
                    $deleteTags = array_diff($oldTags, $noChangedTags);
                    $rtn = $this->setTags($articleid, $addTags);
                    if ($rtn['errorcode'] == 0) {
                        $rtn = $this->deleteTags($articleid, $deleteTags);
                    }
                } else {
                    $rtn = array(
                        'errorcode' => - 1,
                        'errormsg' => 'failed'
                    );
                }
            }
        }
        return $rtn;
    }

    /**
     * 批量保存标签到数据库中
     * 
     * @param int $articleid            
     * @param array $tags
     *            urlencode的值
     * @return array
     */
    public function setTags($articleid, array $tags)
    {
        foreach ($tags as $tag) {
            $result = Business_Tags::getInstance()->setTag(urldecode($tag));
            if ($result['errorcode'] !== 0) {
                return $result;
            } else {
                $resultRel = Business_Tags::getInstance()->setTagAndArticleRel($articleid, $result['result']);
                if ($resultRel['errorcode'] !== 0) {
                    return $resultRel;
                }
            }
        }
        return array(
            'errorcode' => 0,
            'errormsg' => 'success'
        );
    }

    /**
     * 删除指定ID的文章
     * 
     * @param Integer $id            
     * @return Integer
     */
    public function delete($id)
    {
        $db = Utility_Db::getInstance()->conn();
        $where = array(
            $this->_articleTableInfo->id . ' = ?' => $id
        );
        $rows = $db->delete($this->_table, $where);
        if ($rows) {
            $tags = Business_Tags::getInstance()->getTagsInUrlencode($id);
            $rtn = $this->deleteTags($id, $tags);
        } else {
            $rtn = array(
                'errorcode' => - 1,
                'errormsg' => 'failed'
            );
        }
        return $rtn;
    }

    /**
     * 批量删除标签
     * 
     * @param int $articleid            
     * @param array $tags
     *            urlencode的值
     * @return array
     */
    public function deleteTags($articleid, array $tags)
    {
        foreach ($tags as $tag) {
            $tagid = Business_Tags::getInstance()->getTagIdByUrlencode($tag);
            $result = Business_Tags::getInstance()->deleteTagAndArticleRel($articleid, $tagid);
            if ($result['errorcode'] != 0) {
                return $result;
            }
        }
        return array(
            'errorcode' => 0,
            'errormsg' => 'success'
        );
    }

    /**
     * 获得所有文章
     * 
     * @return Array
     */
    public function getAll()
    {
        $select = Utility_Db::getInstance()->conn()->select();
        $select->from($this->_table, "*");
        $stmt = $select->query();
        $result = $stmt->fetchAll();
        return $result;
    }

    /**
     * 通过author id获取author的名字
     * 
     * @param int $id            
     * @return string
     */
    public function getAuthorName($id)
    {
        $table = Zend_Registry::get('database')->author;
        $authorObj = new Business_Author();
        $rtn = $authorObj->getAuthorName($id);
        return $rtn[$table->author];
    }

    /**
     * 获取所有文章所在的年月
     * 
     * @return array
     */
    public function getAllArticleMonth()
    {
        $result = Utility_Db::getInstance()->conn()
            ->select()
            ->from($this->_table, "*")
            ->order('ctime DESC')
            ->query()
            ->fetchAll();
        
        $table = Zend_Registry::get('database')->article;
        $yearMonth = array();
        foreach ($result as $article) {
            $fy = date('F Y', strtotime($article[$table->ctime]));
            if (isset($yearMonth[$fy])) {
                $yearMonth[$fy]['times'] ++;
            } else {
                $yearMonth[$fy]['times'] = 1;
            }
            $yearMonth[$fy]['date'] = date('Y-m', strtotime($article[$table->ctime]));
        }
        return $yearMonth;
    }

    public function getPostTypeById($id)
    {
        $table = Zend_Registry::get('database')->posttype;
        $result = Utility_Db::getInstance()->conn()
            ->select()
            ->from($table->tablename, "*")
            ->where($table->id . '=?', $id)
            ->query()
            ->fetch();
        return $result[$table->name];
    }
}